package com.black.play.listener;

import com.black.play.component.MineWindow;
import com.black.play.constant.AppConstant;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * 主界面全局监听 snake
 *
 * @author ylx
 */
public class MineKeyListener extends KeyAdapter
{
    private MineKeyListener()
    {
    }

    /**
     * 获取单例
     *
     * @return 单例
     */
    public static MineKeyListener getInstance()
    {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 键盘按键监听
     *
     * @param e 按键事件
     */
    @Override
    public void keyPressed(KeyEvent e)
    {
        int keyCode = e.getKeyCode();
        switch (keyCode)
        {
            case KeyEvent.VK_ESCAPE:
                handleEscape();
                break;
            case KeyEvent.VK_SPACE:
                handleSpace();
                break;
        }
    }

    /**
     * 空格
     * 游戏→暂停
     * 暂停→游戏
     * 菜单→开始
     */
    private void handleSpace()
    {
        MineWindow mineWindow = MineWindow.getInstance();
        String activeCard = mineWindow.getActiveCard();
        switch (activeCard)
        {
            case AppConstant.GAME:
                mineWindow.pauseGame();
                break;
            case AppConstant.PAUSE:
                mineWindow.continueGame();
                break;
            case AppConstant.MENU:
                mineWindow.startGame();
                break;
        }
    }

    /**
     * Esc
     * 菜单→退出
     * 暂停→退出
     * 游戏→暂停
     */
    private void handleEscape()
    {
        MineWindow mineWindow = MineWindow.getInstance();
        String activeCard = mineWindow.getActiveCard();
        switch (activeCard)
        {
            case AppConstant.GAME:
                mineWindow.pauseGame();
                break;
            case AppConstant.PAUSE:
            case AppConstant.MENU:
                mineWindow.exitGame();
                break;
        }
    }

    private static class SingletonHolder {
        private static final MineKeyListener INSTANCE = new MineKeyListener();
    }
}
